package com.cal.utms.model.csefileupload;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.cal.utms.dao.csefileupload.CseFileUploadDaoImpl;
import com.cal.utms.dao.maintenance.InstrumentTypeDao;
import com.cal.utms.dao.maintenance.IssuerDaoImpl;
import com.cal.utms.dto.csefileupload.IssuerCodeMappingDto;
import com.cal.utms.entity.Csedownload;
import com.cal.utms.entity.Instrument;
import com.cal.utms.entity.Issuer;
import com.cal.utms.entity.Issuercodemapping;
import com.cal.utms.enumType.InstrumentType;
import com.cal.utms.enumType.InterestRate;
import com.cal.utms.enumType.InterestType;
import com.cal.utms.enumType.WithholdingTax;
import com.cal.utms.util.ValueConvert;

public class CseFileUploadModel {

	CseFileUploadDaoImpl cseFileUploadDaoImpl = new CseFileUploadDaoImpl();

	private InstrumentTypeDao dao = new InstrumentTypeDao();
	private IssuerDaoImpl issuerDaoImpl = new IssuerDaoImpl();

	SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yy", Locale.ENGLISH);
	SimpleDateFormat formatto = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH);

	public void getUnmappingissuerCode(IssuerCodeMappingDto codeMappingDto) {

		List<Csedownload> csedownloads = cseFileUploadDaoImpl.getUnMappingCode();
		if (csedownloads != null) {
			if (csedownloads.size() > 0) {
				for (Csedownload csedownload : csedownloads) {
					String csecode[] = csedownload.getSymbol().split("/");

					IssuerCodeMappingDto codeMappingDto2 = new IssuerCodeMappingDto();
					codeMappingDto2.setCseIsuCode(csecode[0]);
					codeMappingDto2.setCseIsuName(csedownload.getIssuerName());
					codeMappingDto2.setId(csedownload.getId());

					codeMappingDto.getCodeMappingDtos().add(codeMappingDto2);
				}
			}
		}
	}

	public List<String> getAllCSEdownload() {
		List<String> symbols = new ArrayList<String>();
		List<Csedownload> csedownloads = cseFileUploadDaoImpl.getAllRecords();
		for (Csedownload csedownload : csedownloads) {
			symbols.add(csedownload.getSymbol());
		}

		return symbols;
	}

	public void saveUpdateCseDownloads(List<Csedownload> updateCsedownloads, List<Instrument> instruments) throws Exception {
		System.out.println("herg");
		cseFileUploadDaoImpl.saveupdate(updateCsedownloads, instruments);
	}

	public List<String> getMappedCSECode() {
		List<Issuercodemapping> issuercodemappings = cseFileUploadDaoImpl.getMappedCode();
		List<String> codelist = new ArrayList<String>();
		if (issuercodemappings.size() > 0) {
			for (Issuercodemapping issuercodemapping : issuercodemappings) {
				codelist.add(issuercodemapping.getCseIsuCode());
			}
		}
		return codelist;
	}

	public Csedownload getSymbolByData(String isin, String issuerName, String currency, String issuerPrice, String couponType, String couponRate, String paymentPeriod,
			String maturity, String dayCount, String redemptionTerm, String parValue, String dateIssued, String issuedQuantity) {
		Csedownload csedownload = cseFileUploadDaoImpl.getRecords(isin, issuerName, currency, issuerPrice, couponType,
				couponRate.length() > 0 ? ValueConvert.toBigDecimal(couponRate) : BigDecimal.ZERO, paymentPeriod, maturity, dayCount, redemptionTerm,
				ValueConvert.toInteger(parValue), dateIssued, ValueConvert.toBigDecimal(issuedQuantity));

		if (csedownload != null) {
			return csedownload;
		} else {
			return null;
		}

	}

	public Csedownload getBySymbol(String symbol) {
		Csedownload csedownload = cseFileUploadDaoImpl.getbysymbol(symbol);
		return csedownload;
	}

	public void saveMapping(IssuerCodeMappingDto codeMappingDto, String mappings) {

		if (mappings != null) {
			mappings = "{ \"mappings\" : ".concat(mappings) + " }";
			List<Issuercodemapping> issuercodemappings = new ArrayList<Issuercodemapping>();
			List<Instrument> instruments = new ArrayList<Instrument>();
			List<Csedownload> csedownloadsList = new ArrayList<Csedownload>();
			try {
				JSONObject jsonObject = new JSONObject(mappings);
				JSONArray jArray = jsonObject.getJSONArray("mappings");
				for (int i = 0; i < jArray.length(); i++) {
					JSONObject jObj = jArray.getJSONObject(i);
					Issuercodemapping issuercodemapping = new Issuercodemapping();
					issuercodemapping.setCalIssuerCode(jObj.getString("calIssuerCode"));
					issuercodemapping.setCseIsuCode(jObj.getString("cseIsuCode"));
					issuercodemapping.setCseIsuName(jObj.getString("cseIsuName"));
					issuercodemapping.setIssuer(issuerDaoImpl.getIssuerByIssuerCode(jObj.getString("calIssuerCode")));
					issuercodemappings.add(issuercodemapping);
					System.out.println("herr");
					List<Csedownload> csedownloads = cseFileUploadDaoImpl.getCserecordByIssuerCode(issuercodemapping.getCseIsuName());
					for (Csedownload csedownload : csedownloads) {
						System.out.println("1");
						Instrument instrument = createNONGOVTInstrument(csedownload, issuercodemapping.getIssuer());
						if (instrument != null) {
							if (instrument.getInstrumentType() != null) {
								instruments.add(instrument);
								csedownload.setStatus("Complite");
								csedownload.setIssuerMapping("Mapped");
							} else {
								csedownload.setStatus("Not Complite");
								csedownload.setIssuerMapping("Mapped");
							}
						} else {
							csedownload.setStatus("Not Complite");
							csedownload.setIssuerMapping("Mapped");
						}
						csedownloadsList.add(csedownload);
					}
				}

				Object object = cseFileUploadDaoImpl.saveMapping(issuercodemappings, instruments, csedownloadsList);
				if (object instanceof Integer) {
					codeMappingDto.setId((Integer) object);
					codeMappingDto.setSuccess(true);
					codeMappingDto.setResulteMsg("SUCCESS");
				} else {
					codeMappingDto.setSuccess(false);
					codeMappingDto.setResulteMsg("There is some error returned from the server.");
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

	}

	public Instrument createGOVTInstrument(String[] cseline) {
		System.out.println("jehdhe");
		Instrument instrument = new Instrument();
		instrument.setIssuer(issuerDaoImpl.getById(1));
		instrument.setInstrumentCode(cseline[0].trim());
		instrument.setLabel(cseline[1].trim());
		if (cseline[6].trim().length() > 0)
			instrument.setCouponRate(ValueConvert.toBigDecimal(cseline[6].trim()));
		else
			instrument.setCouponRate(BigDecimal.ZERO);
		instrument.setMinDenominal(ValueConvert.toBigDecimal(cseline[11].trim()));
		instrument.setDayBasis(convertDaybasis(cseline[9].trim()));
		try {
			instrument.setIssueDate(format.parse(cseline[12].trim()));
			instrument.setMaturityDate(format.parse(cseline[8].trim()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		instrument.setStatus("FREE");
		if (cseline[7].trim().equals("Bi-Annual")) {
			instrument.setCouponFreq(6);
			instrument.setInstrumentType(dao.getInstumentByfactors(InstrumentType.G, 6, convertDaybasis(cseline[9].trim())));
		} else {
			instrument.setCouponFreq(0);
			instrument.setInstrumentType(dao.getInstumentByfactors(InstrumentType.G, 0, convertDaybasis(cseline[9].trim())));
		}
		return instrument;
	}

	private String convertDaybasis(String string) {
		if (string.equals("Actual/Actual")) {
			return "Act / Act";
		} else if (string.equals("Actual/365")) {
			return "Act / 365";
		} else if (string.equals("Actual/364")) {
			return "Act / 364";
		} else if (string.equals("Actual/360")) {
			return "Act / 360";
		} else if (string.equals("30/360")) {
			return "30 / 360";
		} else if (string.equals("30/365")) {
			return "30 / 365";
		}
		return "Vary";
	}

	public Instrument createNONGOVTInstrument(String[] cseline) {
		Instrument instrument = new Instrument();
		Issuer issuer = issuerDaoImpl.getMappingIssuer(cseline[0].trim().split("/")[0]);
		if (issuer != null)
			instrument.setIssuer(issuer);
		else
			instrument.setIssuer(null);
		instrument.setInstrumentCode(cseline[0].trim());
		instrument.setLabel(cseline[1].trim());
		if (cseline[6].trim().length() > 0)
			instrument.setCouponRate(ValueConvert.toBigDecimal(cseline[6].trim()));
		else
			instrument.setCouponRate(BigDecimal.ZERO);
		instrument.setMinDenominal(ValueConvert.toBigDecimal(cseline[11].trim()));
		instrument.setDayBasis(convertDaybasis(cseline[9].trim()));
		try {
			instrument.setIssueDate(format.parse(cseline[12].trim()));
			instrument.setMaturityDate(format.parse(cseline[8].trim()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		instrument.setStatus("FREE");

		instrument.setCouponFreq(6);
		byte denominals = (byte) (cseline[11].trim() != null ? 1 : 0);
		InterestRate interestRate = cseline[5].trim().equals("Fixed") ? InterestRate.F : InterestRate.V;
		byte coupon;
		if (cseline[6].trim().length() > 0)
			coupon = (byte) 2;
		else
			coupon = 0;
		int couFreQ = 0;
		if (cseline[7].trim().equals("Bi-Annual")) {
			couFreQ = 6;
		} else if (cseline[7].trim().equals("Annual")) {
			couFreQ = 12;
		} else if (cseline[7].trim().equals("Monthly")) {
			couFreQ = 1;
		} else if (cseline[7].trim().equals("Quarterly")) {
			couFreQ = 3;
		} else {
			couFreQ = 0;
		}

		com.cal.utms.entity.InstrumentType instrumentType = dao.getInstumentByAllfactors(InstrumentType.O, (byte) 0, denominals, (byte) 1, WithholdingTax.N, interestRate,
				InterestType.S, convertDaybasis(cseline[9].trim()), coupon, couFreQ, (byte) 0, (byte) 2);

		if (instrumentType != null) {
			instrument.setInstrumentType(instrumentType);
		} else {
			instrument.setInstrumentType(null);
		}
		return instrument;
	}

	public Instrument createNONGOVTInstrument(Csedownload csedownload, Issuer issuer) {
		Instrument instrument = new Instrument();

		if (issuer != null)
			instrument.setIssuer(issuer);
		else
			instrument.setIssuer(null);
		instrument.setInstrumentCode(csedownload.getSymbol());
		instrument.setLabel(csedownload.getIsin());
		instrument.setCouponRate(csedownload.getCouponRate());

		instrument.setMinDenominal(BigDecimal.valueOf(csedownload.getParValue()));
		instrument.setDayBasis(convertDaybasis(csedownload.getDayCount()));
		try {
			instrument.setIssueDate(format.parse(csedownload.getDateIssued()));
			instrument.setMaturityDate(format.parse(csedownload.getMaturity()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		instrument.setStatus("FREE");

		byte denominals = (byte) (csedownload.getParValue() != 0 ? 1 : 0);
		InterestRate interestRate = csedownload.getCouponType().equals("Fixed") ? InterestRate.F : InterestRate.V;
		byte coupon;
		if (csedownload.getCouponRate().compareTo(BigDecimal.ZERO) == 1)
			coupon = (byte) 2;
		else
			coupon = 0;
		int couFreQ = 0;
		if (csedownload.getPaymentPeriod().equals("Bi-Annual")) {
			instrument.setCouponFreq(6);
			couFreQ = 6;
		} else if (csedownload.getPaymentPeriod().equals("Annual")) {
			instrument.setCouponFreq(12);
			couFreQ = 12;
		} else if (csedownload.getPaymentPeriod().equals("Monthly")) {
			instrument.setCouponFreq(1);
			couFreQ = 1;
		} else if (csedownload.getPaymentPeriod().equals("Quarterly")) {
			instrument.setCouponFreq(3);
			couFreQ = 3;
		} else {
			instrument.setCouponFreq(0);
			couFreQ = 0;
		}

		com.cal.utms.entity.InstrumentType instrumentType = dao.getInstumentByAllfactors(InstrumentType.O, (byte) 0, denominals, (byte) 1, WithholdingTax.N, interestRate,
				InterestType.S, convertDaybasis(csedownload.getDayCount()), coupon, couFreQ, (byte) 0, (byte) 2);

		if (instrumentType != null) {
			instrument.setInstrumentType(instrumentType);
		} else {
			instrument.setInstrumentType(null);
		}
		return instrument;
	}
}
